<template>
  <div class="number-rolling-container">
    <div class="number-display" ref="numberRef">
      <span v-for="(char, index) in displayNumber" :key="index" class="digit-item">
        {{ char }}
      </span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue';

const props = defineProps({
  // 目标数字，可以是亿级别的数字
  targetNumber: {
    type: Number,
    default: 999999999
  },
  // 动画持续时间（毫秒）
  duration: {
    type: Number,
    default: 3000
  },
  // 刷新间隔（毫秒）
  interval: {
    type: Number,
    default: 30
  }
});

// 显示的数字
const displayNumber = ref('0');
// 数字元素引用
const numberRef = ref(null);

// 格式化数字为带千分位的字符串
const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

// 开始数字翻滚动画
const startRolling = () => {
  let startTime = null;
  const startValue = 0;
  const endValue = props.targetNumber;
  const totalFrames = Math.ceil(props.duration / props.interval);
  let currentFrame = 0;
  
  // 动画函数
  const animate = (timestamp) => {
    if (!startTime) startTime = timestamp;
    const progress = Math.min((timestamp - startTime) / props.duration, 1);
    
    // 使用缓动函数使动画更自然
    const easeOutQuad = (t) => t * (2 - t);
    const easedProgress = easeOutQuad(progress);
    
    // 计算当前值
    const currentValue = Math.floor(startValue + (endValue - startValue) * easedProgress);
    
    // 更新显示的数字
    displayNumber.value = formatNumber(currentValue);
    
    // 继续动画
    if (progress < 1) {
      requestAnimationFrame(animate);
    }
  };
  
  // 开始动画
  requestAnimationFrame(animate);
};

// 组件挂载后初始化
onMounted(() => {
  // 初始显示为0
  displayNumber.value = formatNumber(0);
  startRolling()
});
</script>

<style scoped>

</style>
